package com.ruoyi.web.controller.common;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.zhyd.oauth.cache.AuthDefaultStateCache;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

import static com.ruoyi.common.utils.AuthUtils.getAuthRequest;

/**
 * @description:AuthController
 * @author: caoes
 * create:2023/6/27 17:16
 **/
@RestController
@RequestMapping("login/{appId}")
public class AuthController {

    @RequestMapping("/render/{source}")
    public void renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
        String redirectUri = "http://utkaex.natappfree.cc/login/callback/"+source;
        AuthRequest authRequest = getAuthRequest(source,"wx08c1d5eababe844d","73696133d4351133aa752afed21fe212",redirectUri, AuthDefaultStateCache.INSTANCE);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        System.out.println(authorizeUrl);
        response.sendRedirect(authorizeUrl);
    }

    @RequestMapping("/callback/{source}")
    public ModelAndView login(@PathVariable("source") String source, AuthCallback callback, HttpServletRequest request) {
        AuthRequest authRequest = getAuthRequest(source,"wx08c1d5eababe844d","73696133d4351133aa752afed21fe212","http://utkaex.natappfree.cc", AuthDefaultStateCache.INSTANCE);
        AuthResponse<AuthUser> response = authRequest.login(callback);

        if (response.ok()) {
            System.out.println(response.getMsg());
            System.out.println(response.getData().toString());
        }


        return new ModelAndView("error", new HashMap<>());
    }

    //微信对接
    @Autowired
    private WxMpService wxMpService;

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private WxMpMessageRouter wxMpMessageRouter;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String auth(@PathVariable String appId,
                       @RequestParam(name = "signature",required = true) String signature,
                       @RequestParam(name = "timestamp",required = true) String timestamp,
                       @RequestParam(name = "nonce",required = true) String nonce,
                       @RequestParam(name = "echostr",required = true) String echostr) {

        logger.info("接收到来自微信服务器的认证消息, signature:{}, timestamp:{}, nonce:{} ,echostr:{}",signature,timestamp,nonce,echostr);
        if (!this.wxMpService.switchover(appId)) {
            throw new IllegalArgumentException();
        }
        if (wxMpService.checkSignature(timestamp,nonce,signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openId,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        logger.info("接收微信请求：[openId={}, signature={}, encType={}, msgSignature={}, timestamp={}, nonce={], requestBody={} ", openId, signature, encType, msgSignature, timestamp, nonce, requestBody);
        if (!this.wxMpService.switchover(appId)) {
            throw new IllegalArgumentException();
        }
        if (!wxMpService.checkSignature(timestamp,nonce,signature)) {
            throw new IllegalArgumentException();
        }
        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            logger.debug("消息解密后内容为：{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        logger.debug("组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.wxMpMessageRouter.route(message);
        } catch (Exception e) {
            logger.error("路由消息时出现异常！", e);
        }

        return null;
    }

}
